package com.etrans.web.gps.common.message;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.ui.velocity.VelocityEngineUtils;



/**
 * 邮件发送工具类
 * @author jw.chen
 *
 */
public class MailSendUtil {
    private final static String host = "smtp.163.com"; //163的服务器
    private final static String formName = "realcyi@163.com";//你的邮箱
    private final static String password = "ct20090509"; //授权码
    private final static String replayAddress = "realcyi@163.com"; //你的邮箱
        

    private static  VelocityEngine velocityEngine = null;
    private static  Map<String, Object> proMap = null;

    /**
     * 发送html格式文本
     * @param info		邮件对象实体类
     * @param model		模块里面用到的参数赋值
     * @throws Exception
     */
    public static boolean sendHtmlMail(MailInfo info,Map<String,Object> model)throws Exception{
        try {
			info.setHost(host);
			info.setFormName(formName);
			info.setFormPassword(password);   //网易邮箱的授权码~不一定是密码
			info.setReplayAddress(replayAddress);

			Message message = getMessage(info);
			// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			String text = VelocityEngineUtils.mergeTemplateIntoString(MailSendUtil.getVelocityEngineInstance(), info.getFileName(), "UTF-8", model);
			html.setContent(text, "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			// 将MiniMultipart对象设置为邮件内容
			message.setContent(mainPart);
			Transport.send(message);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
       return false;
    }

    public static void sendTextMail(MailInfo info) throws Exception {

        info.setHost(host);
        info.setFormName(formName);
        info.setFormPassword(password);   //网易邮箱的授权码~不一定是密码
        info.setReplayAddress(replayAddress);
        Message message = getMessage(info);
        //消息发送的内容
        message.setText(info.getContent());

        Transport.send(message);
    }
    
    public static  VelocityEngine getVelocityEngineInstance() {
        proMap = new HashMap<String, Object>();
        proMap.put("resource.loader", "class");
        proMap.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        
        if (null == velocityEngine) {
            synchronized (VelocityEngine.class) {
                if (null == velocityEngine) {
                    velocityEngine = new VelocityEngine();
                    for (Map.Entry<String, Object> entry : proMap.entrySet()) {
                        velocityEngine.setProperty(entry.getKey(), entry.getValue());
                    }
                }
            }
        }
        return velocityEngine;
    }

    private static Message getMessage(MailInfo info) throws Exception{
        final Properties p = System.getProperties() ;
        p.setProperty("mail.smtp.host", info.getHost());
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.user", info.getFormName());
        p.setProperty("mail.smtp.pass", info.getFormPassword());

        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session session = Session.getInstance(p, new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
            }
        });
        session.setDebug(true);
        Message message = new MimeMessage(session);
        //消息发送的主题
        message.setSubject(info.getSubject());
        //接受消息的人
        message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
        //消息的发送者
        message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"车辆联网联控平台"));
        // 创建邮件的接收者地址，并设置到邮件消息中
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(info.getToAddress()));
        // 消息发送的时间
        message.setSentDate(new Date());

        return message ;
    }
    
    /**
     * 
     * @param EmailAddr 	收件方邮箱地址;
     * @param title			邮件标题;
     * @param nickname		收件方昵称;
     * @param EmailMessage	邮件内容;
     * @return result		发送结果:1、"success" 发送成功,2、"error" 发送失败
     */
    @SuppressWarnings("finally")
	public static String sendEmail(String EmailAddr,String title,String nickname,String EmailMessage){
    	String result = ""; 
    	try {
	        MailInfo info = new MailInfo();
	        info.setToAddress(EmailAddr);
	        info.setSubject(title);
	        info.setFileName("Email.html");
	        Map<String,Object> model = new HashMap<String,Object>();
	        model.put("userName",nickname);
	        model.put("tips",EmailMessage);
            MailSendUtil.sendHtmlMail(info,model);
            result="success";
        } catch (Exception e) {
        	result="error";
            System.out.print("邮件发送失败！");
            e.printStackTrace();
        }finally{
        	return result;
        }
    }
    
    public static void main(String[] args) {
    	try {
	    	String mail = "wrw@e-trans.com.cn"; //发送对象的邮箱
	        String title = "报警处理提醒";
	        MailInfo info = new MailInfo();
	        info.setToAddress(mail);
	        info.setSubject(title);
	        //发送html格式
	        info.setFileName("Email.html");
	        Map<String,Object> model = new HashMap<String,Object>();
	        model.put("userName","亿程");
	        model.put("tips", "贵公司车牌【粤AV6738】于【2018-03-13 09:42:36】提示【超速】报警； 请核查，谢谢ha!");
            MailSendUtil.sendHtmlMail(info,model);    
        } catch (Exception e) {
            System.out.print("邮件发送失败！");
            e.printStackTrace();
        }
	}
}